package com.qdlc.p2p.biz.task.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.qdlc.p2p.biz.processor.event.BorrowValueEvent;
import com.qdlc.p2p.biz.processor.task.collection.TenderTaskProcessor;
import com.qdlc.p2p.biz.service.AutoBorrowService;
import com.qdlc.p2p.biz.service.BorrowService;
import com.qdlc.p2p.biz.service.TppInvestService;
import com.qdlc.p2p.biz.service.UserAutoTenderLogService;
import com.qdlc.p2p.biz.task.AbstractLoanTask;
import com.qdlc.p2p.biz.task.JobQueue;
import com.qdlc.p2p.biz.task.ValueEvent;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.core.queue.QueueHandlers;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.util.BeanUtil;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.MessageUtil;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserAutoTenderLog;
import com.qdlc.p2p.dal.model.BorrowModel;
import com.qdlc.p2p.dal.model.UserAutoTenderLogModel;

/**
 * 
 * @Title: TenderTask.java
 * @Package com.rd.p2p.core.quartz.task
 * @Description: 投标业务处理类
 * @author Moon.Liu
 * @date 2014年12月2日 上午10:56:03
 * @version V2.0
 */
public class TenderTask extends AbstractLoanTask {
	private Logger logger = Logger.getLogger(TenderTask.class);

	public TenderTask() {
		super();
		task.setName("Tender.Task");
	}

	@SuppressWarnings("unchecked")
	@Override
	public void doLoan() {

		JobQueue<ValueEvent> queue = JobQueue.getTenderInstance();
		AutoBorrowService autoBorrowService = (AutoBorrowService) BeanUtil.getBean("autoBorrowService");
		TppInvestService tppInvestService = (TppInvestService) BeanUtil.getBean("tppInvestService");
		BorrowService borrowService = (BorrowService) BeanUtil.getBean("borrowService");
		UserAutoTenderLogService userAutoTenderLogService = (UserAutoTenderLogService) BeanUtil.getBean("userAutoTenderLogService");
		while (!queue.isEmpty()) {
			ValueEvent event = queue.peek();
			if (event != null) {
				String result = "success";
				try {
					if ("tender".equals(event.getOperate())) {
//						tppInvestService.addTender(event.getBorrowModel());
					} else if ("autoTender".equals(event.getOperate())) {
						autoBorrowService.autoDealTender(event.getBorrowModel());
					} else if ("doAddTender".equals(event.getOperate())) {
                        // 投标代收后-处理
						logger.info("代收投资金(1001)业务队列处理(代收回调后) START 订单号[" + event.getBorrowModel().getTenderBilNo() + "]");
						tppInvestService.addTppTender(event.getBorrowModel());
					} else if("tppAutoTender".equals(event.getOperate())){
						
						BorrowValueEvent borrEvent = new BorrowValueEvent();
						BorrowModel borrowModel = BorrowModel.instance(event.getBorrow());
						borrowModel.setMoney(event.getMoney());
						User tenderUser = event.getUser();
						// 封装用户扩展参数
				        Map map = new HashMap<String, Object>();
				        long[] redIds = borrowModel.getRedEnvelopeIds();
				        map.put("redIds", redIds == null ? null : redIds); // 红包IDS
				        map.put("type", borrowModel.getType()); // 标的类型
				        map.put("uuid", borrowModel.getUuid()); // 标ID
				        map.put("tppUserCustId", tenderUser.getTppUserCustId()); // 用户新浪标识ID

				        long rateInterestId = borrowModel.getRateInterestId();
				        map.put("rateId", rateInterestId == 0 ? null : rateInterestId); // 加息券ID
				        borrowModel.setParam(JSON.toJSONString(map));
				        borrowModel.setTenderType(Byte.parseByte("1"));// 设置投标类型为：自动投标
						
						borrEvent.setBorrowModel(borrowModel);
						borrEvent.setTaskProcessorClass(TenderTaskProcessor.class);
						borrEvent.setUser(tenderUser);
						borrEvent.setClientIp(Global.getIP());
				        //将事件放入到队列中
				        QueueHandlers.put(borrEvent);
					} else if("doAutoTender".equals(event.getOperate())){
					    // 自动投标代收后-处理
						tppInvestService.autoTenderHander(event.getBorrowModel());
					}
				} catch (Exception e) {
					logger.error(e.getMessage(), e);
					if (e instanceof BusinessException) {// 业务异常，保存业务处理信息
						result = e.getMessage();
					} else {
						result = "系统异常，业务处理失败";
					}
					//如果自动投标出现异常，那么插入自动投标失败记录
					if("tppAutoTender".equals(event.getOperate()) && event.getUser() != null && event.getBorrow() != null){
						UserAutoTenderLog userAutoTenderLog = new UserAutoTenderLog();
						userAutoTenderLog.setUser(event.getUser());
						userAutoTenderLog.setBorrow(event.getBorrow());
						userAutoTenderLog.setAddTime(DateUtil.getNow());
						userAutoTenderLog.setStatus(UserAutoTenderLogModel.TENDER_FAIL);
						userAutoTenderLog.setRemark(MessageUtil.getMessage("MF105001011"));
						userAutoTenderLogService.save(userAutoTenderLog);
					}
					//发送邮件
					MailUtil.sendMail("投标队列异常",e);
				} finally {
					String isLastFlag = event.getLastflag();
					long borrowId = 0;
					if(event.getBorrow() != null){
						borrowId = event.getBorrow().getId();
					}
					queue.remove(event);
					if("tppAutoTender".equals(event.getOperate()) && isLastFlag.equals("lastFlag") && borrowId > 0){
						try{
							borrowService.updateStatus(borrowId, 1, 19);
						}catch(Exception e){
							logger.error(e.getMessage());
						}
					}
				}
				if (event.getResultFlag() != null) {// 在需要保存系统处理信息的地方直接保存进来
					Global.TASK_RESULT_MAP.put(event.getResultFlag(), result);
				}
			}
		}

	}

	@Override
	public Object getLock() {
		return TenderTask.TENDER_STATUS;
	}

}
